package com.gpframework.module.purchase.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.gpframework.common.config.GpframeworkConfig;
import com.gpframework.common.constant.Constants;
import com.gpframework.common.utils.DateUtils;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.common.utils.uuid.IdUtils;
import com.gpframework.module.purchase.domain.GpPurchaseReceipt;
import com.gpframework.module.purchase.domain.req.GpPurchaseTrackUpdate;
import com.gpframework.module.purchase.service.IGpPurchaseReceiptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gpframework.module.purchase.mapper.GpPurchaseTrackMapper;
import com.gpframework.module.purchase.domain.GpPurchaseTrack;
import com.gpframework.module.purchase.domain.vo.GpPurchaseTrackVo;
import com.gpframework.module.purchase.service.IGpPurchaseTrackService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
/**
 * @ClassName GpPurchaseTrack
 * @Author gpframework
 * @Date 2023-12-22
 * @Version 1.0.0
 * @Description 采购跟踪单Service业务层处理
 */
@Service
public class GpPurchaseTrackServiceImpl extends ServiceImpl<GpPurchaseTrackMapper, GpPurchaseTrack> implements IGpPurchaseTrackService {

    @Autowired
    private IGpPurchaseReceiptService iGpPurchaseReceiptService;

    /**
     * @Description 查询列表返回VO 用于返回给前端的列表接口
     * @Author gpframework
     * @Date 2023-12-22
     * @Param [lqw]
     * @Return List<GpPurchaseTrackVo>
     */
    @Override
    public List<GpPurchaseTrackVo> listVo(QueryWrapper<GpPurchaseTrack> lqw) {
        return this.baseMapper.listVo(lqw);
    }

    /**
     * @Description 通过查询详情VO 用于返回给前端的列详情接口
     * @Author gpframework
     * @Date 2023-12-22
     * @Param [id]
     * @Return GpPurchaseTrackVo
     */
    @Override
    public GpPurchaseTrackVo getVoById(Long id) {
        return this.baseMapper.getVo(id);
    }

    /**
     * 生成采购跟踪单
     * @param ids
     * @param createBy
     * @return
     */
    @Override
    public boolean createPurchaseTrack(List<Long> ids, String createBy) {
        GpPurchaseReceipt gpPurchaseReceipt;
        GpPurchaseTrack gpPurchaseTrack;
        for (Long id : ids) {
            gpPurchaseReceipt = iGpPurchaseReceiptService.getById(id);
            if (gpPurchaseReceipt == null) {
                continue;
            }
            gpPurchaseTrack = Convert.convert(new TypeReference<GpPurchaseTrack>() {}, gpPurchaseReceipt);
            if (StringUtils.isNotBlank(createBy)) {
                gpPurchaseTrack.setCreateBy(createBy);
            }
            gpPurchaseTrack.setProductionApplicationId(gpPurchaseReceipt.getProductionApplicationId());
            gpPurchaseTrack.setPurchasingDetailsId(gpPurchaseReceipt.getPurchasingDetailsId());
            gpPurchaseTrack.setProcureSchedulingId(gpPurchaseReceipt.getProcureSchedulingId());
            gpPurchaseTrack.setPurchaseReceiptId(gpPurchaseReceipt.getId());
            gpPurchaseTrack.setRelatedReceiveNumber(gpPurchaseReceipt.getRelatedOrderNumber());
            this.init(gpPurchaseTrack);
            boolean save = this.save(gpPurchaseTrack);
            if (save) {
                // 生成采购跟踪二维码
                gpPurchaseTrack.setOrderQrCode(this.getQrCode(gpPurchaseTrack.getId()));
                this.updateById(gpPurchaseTrack);
            }
        }
        return true;
    }

    /**
     * 生成采购跟踪二维码
     * @param id 采购跟踪id
     * @return
     */
    private String getQrCode(Long id) {
        if (id == null) {
            return null;
        }
        String date = DateUtils.datePath();
        String uuid = IdUtils.fastUuid();
        String filePath = GpframeworkConfig.getUploadPath() + "/" + date + "/" + uuid + ".jpg";
        File file = FileUtil.file(filePath);
        if (!file.exists()) {
            // 文件不存在，创建新文件
            FileUtil.touch(file);
        }
        QrCodeUtil.generate("id=" + id + "&type=2", 300, 300, file);
        return Constants.RESOURCE_PREFIX + "/upload/" + date + "/" + uuid + ".jpg";
    }

    @Override
    public boolean edit(List<GpPurchaseTrackUpdate> list) {
        List<GpPurchaseTrack> updateList = new ArrayList<>();
        GpPurchaseTrack gpPurchaseTrack;
        for (GpPurchaseTrackUpdate gpPurchaseTrackUpdate : list) {
            gpPurchaseTrack = Convert.convert(new TypeReference<GpPurchaseTrack>() {}, gpPurchaseTrackUpdate);
            this.init(gpPurchaseTrack);
            updateList.add(gpPurchaseTrack);
        }
        return this.updateBatchById(updateList);
    }

    @Override
    public boolean editOne(GpPurchaseTrackUpdate gpPurchaseTrackUpdate) {
        GpPurchaseTrack gpPurchaseTrack = Convert.convert(new TypeReference<GpPurchaseTrack>() {}, gpPurchaseTrackUpdate);
        this.init(gpPurchaseTrack);
        return this.updateById(gpPurchaseTrack);
    }

    @Override
    public boolean copy(Long id, Integer copyNum) {
        GpPurchaseTrack gpPurchaseTrack = this.getById(id);
        if (gpPurchaseTrack == null) {
            return false;
        }
        for (int i = 0; i < copyNum; i++) {
            gpPurchaseTrack.setId(null);
            this.save(gpPurchaseTrack);
        }
        return true;
    }

    private void init(GpPurchaseTrack gpPurchaseTrack) {
        // 计算损耗=进仓重量-成品净重
        if (gpPurchaseTrack.getDyeingIntoNum() != null && gpPurchaseTrack.getFinishProductWeight() != null) {
            BigDecimal dyeingIntoNum = BigDecimal.valueOf(gpPurchaseTrack.getDyeingIntoNum());
            gpPurchaseTrack.setLossWeight(dyeingIntoNum.subtract(gpPurchaseTrack.getFinishProductWeight()));
            // 计算损耗率=损耗/染厂进仓数量
            gpPurchaseTrack.setLossRate(gpPurchaseTrack.getLossWeight().multiply(BigDecimal.valueOf(100)).divide(dyeingIntoNum, 2, RoundingMode.HALF_UP));
            // 计算损耗差异=损耗率%-正常损耗值%
            if (gpPurchaseTrack.getNormalLossValue() != null) {
                gpPurchaseTrack.setLossDiff(gpPurchaseTrack.getLossRate().subtract(gpPurchaseTrack.getNormalLossValue()));
            }
            // 计算胚布出码率=成品总足码数-胚布进仓数量
            if (gpPurchaseTrack.getFinishProductQuantitySufficient() != null) {
                gpPurchaseTrack.setGreyClothOutputRate(gpPurchaseTrack.getFinishProductQuantitySufficient().subtract(dyeingIntoNum));
                // 计算成品出码率=成品总足码数-成品净重数量
                if (gpPurchaseTrack.getFinishProductWeight() != null) {
                    gpPurchaseTrack.setFinishProductOutputRate(gpPurchaseTrack.getFinishProductQuantitySufficient().subtract(gpPurchaseTrack.getFinishProductWeight()));
                }
            }
        }
    }
}
